package cn.jesin.css.controller;

import cn.hutool.core.util.StrUtil;
import cn.jesin.css.common.Flag;
import cn.jesin.css.common.RedisKeyFlag;
import cn.jesin.css.utils.DataCheckUtil;
import cn.jesin.css.utils.VerificationCodeUtil;
import cn.jesin.css.vo.responseformat.Code;
import cn.jesin.css.vo.responseformat.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author 谷汉斌
 * @description 手机验证码控制器
 * @createTime 2024/8/15 下午8:35
 */
@Tag(name = "手机验证码控制器", description = "处理手机验证码相关请求")
@RestController
public class PhoneVerificationCodeController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private VerificationCodeUtil verificationCodeUtil;

    /**
     * 发送手机验证码
     */
    @Operation(summary = "发送手机验证码")
    @GetMapping("/phone-code")
    public Result<String> sendVerificationCode(@RequestParam(value = "phone") String phone) {
        //校验手机号
        if (DataCheckUtil.isValidPhoneNumber(phone)) {
            //从redis中获取验证码
            String code = redisTemplate.opsForValue().get(phone + RedisKeyFlag.PHONE_CODE);
            if (StrUtil.isBlank(code)) {
                //发送验证码
                code = verificationCodeUtil.sendVerificationCode(phone);
                if (StrUtil.isNotBlank(code)) {
                    //对code加密
                    code = new BCryptPasswordEncoder().encode(code);
                    //存入redis,60秒后过期
                    redisTemplate.opsForValue().set(phone + RedisKeyFlag.PHONE_CODE, code, 3960, TimeUnit.SECONDS);
                    return Result.<String>builder()
                            .flag(Flag.SUCCESS.isCode())
                            .code(Code.CODE_SEND_SUCCESS.getCode())
                            .message(Code.CODE_SEND_SUCCESS.getInfo())
                            .build();
                }
            } else {
                return Result.<String>builder()
                        .flag(Flag.SUCCESS.isCode())
                        .code(Code.CODE_SEND_SUCCESS.getCode())
                        .message(Code.CODE_SEND_SUCCESS.getInfo())
                        .build();
            }
        }
        return Result.<String>builder()
                .flag(Flag.FAIL.isCode())
                .code(Code.CODE_SEND_FAIL.getCode())
                .message(Code.CODE_SEND_FAIL.getInfo())
                .build();
    }
}
